<?php
class Question extends Admin_Controller
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('user_model','user');
		$this->load->model('question_model','question');
		$this->load->model('answer_model','answer');
	}
	
	function index()
	{
		$data['result'] = $this->question->order_by('id desc')->get();
		$data['pagination'] = $this->question->pagination();
		$this->template->build('question_index',$data);
	}
	
	function view($id)
	{
		$data['question'] = $this->question->get_row($id);
		$data['answers'] = $this->answer->where('question_id = '.$id)->get();
		$data['pagination'] = $this->answer->pagination();
		$this->template->build('question_view',$data);
	}
	
	function form($id = NULL)
	{
		$data['rs'] = $this->question->get_row($id);
		$this->template->append_metadata(js_validate());
		$this->template->build('question_form',$data);
	}
	
	function answer_form($id = NULL)
	{
		$data['rs'] = $this->answer->get_row($id);
		$this->template->build('answer_form',$data);
	}
	
	function save()
	{
		if($_POST)
		{
			if(empty($_POST['id']))
			{
				$_POST['user_id'] = $this->session->userdata('id');
				$_POST['created'] = time();
			}
			else
			{
				$_POST['updated'] = time();
			}
			$this->question->save($_POST);
		}
		set_notify('success', 'ตั้งคำถามเรียบร้อยแล้วค่ะ');
		redirect('question');
	}
	
	function answer_save()
	{
		if($_POST)
		{
			if(empty($_POST['id']))
			{
				$_POST['user_id'] = $this->session->userdata('id');
				$_POST['created'] = time();
			}
			else
			{
				$_POST['updated'] = time();
			}
			$this->answer->save($_POST);
		}
		set_notify('success', 'ตอบคำถามเรียบร้อยแล้วค่ะ');
		redirect('question/view/'.$_POST['question_id']);
	}
	
	function answer_delete($id)
	{
		$this->answer->delete('id',$id);
		set_notify('success', 'ลบคำตอบเรียบร้อยแล้วค่ะ');
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	function delete($id)
	{
		$this->answer->detlete('question_id',$id);
		$this->question->delete($id);
		set_notify('success', 'ลบคำถามเรียบร้อยแล้วค่ะ');
		redirect('question');
	}
	
}
?>